import 'dart:convert' as convert;
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_shop/res/colors.dart';
import 'package:oktoast/oktoast.dart' as okToast;
import 'package:oktoast/oktoast.dart';
import 'package:url_launcher/url_launcher.dart';

///Title:常规工具类 <br/>
///Description: <br/>
///author:xiemiao <br/>
///date: 2020-02-17 <br/>
///version 1.0 <br/>
class Utils {
  ///是否是生产环境
  static const bool isProd = const bool.fromEnvironment("dart.vm.product");

  ///字符串是否为空
  static bool strIsEmpty(String str) {
    return str == null || str.trim().isEmpty;
  }

  ///字符串非空
  static bool strIsNotEmpty(String str) {
    return str != null && str.trim().isNotEmpty;
  }

  ///比较字符串是否相等
  static bool strEquals(String a, String b) {
    return (a == null && b == null) || (a != null && b != null && a == b);
  }

  ///展示snackBar
  static void showSnackBar(BuildContext context, String str) {
    Scaffold.of(context).showSnackBar(SnackBar(
      content: Text(str),
      duration: Duration(milliseconds: 800),
    ));
  }

  ///展示toast
  static void showToast(
    String str, {
    BuildContext context,
    Duration duration,
    ToastPosition position = ToastPosition.bottom,
    TextStyle textStyle,
    EdgeInsetsGeometry textPadding,
    Color backgroundColor,
    double radius,
    VoidCallback onDismiss,
    TextDirection textDirection,
    bool dismissOtherToast = true,
    TextAlign textAlign,
    OKToastAnimationBuilder animationBuilder,
    Duration animationDuration,
    Curve animationCurve,
  }) {
    okToast.showToast(
      str,
      position: position,
      backgroundColor: CommonColors.primary.withOpacity(0.8),
      dismissOtherToast: dismissOtherToast,
    );
  }

  ///展示toast widget
  static void showToastWidget(
    Widget widget, {
    BuildContext context,
    Duration duration,
    ToastPosition position,
    VoidCallback onDismiss,
    bool dismissOtherToast = true,
    TextDirection textDirection,
    bool handleTouch,
    OKToastAnimationBuilder animationBuilder,
    Duration animationDuration,
    Curve animationCurve,
  }) {
    okToast.showToastWidget(
      widget,
      dismissOtherToast: dismissOtherToast,
    );
  }

  ///拨打电话
  static void callPhone(String phone) async {
    String url = "tel:$phone";
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw "电话格式不正确";
    }
  }

  ///对象转json
  static String parseObj2Json(Object obj) {
    return convert.json.encode(obj);
  }

  ///json转map
  static Map<String, dynamic> parseJson2Map(String json) {
    return convert.json.decode(json);
  }

  ///json转对象
  static T parseJson2Obj<T>(String json, T f(Map v)) {
    Map<String, dynamic> map = parseJson2Map(json);
    return f(map);
  }

  ///json转 list
  static List<dynamic> parseJson2List(String json) {
    return convert.json.decode(json);
  }

  ///json转obj list
  static List<T> parseJson2ObjList<T>(String json, T f(Map v), {List<T> defValue = const []}) {
    List<dynamic> dynamicList = parseJson2List(json);
    List<T> list = dynamicList?.map((v) => f(v))?.toList();
    return list ?? defValue;
  }

  ///post延迟任务
  static void postDelayed(int milliseconds, callback) {
    Future.delayed(Duration(milliseconds: milliseconds), callback);
  }

  ///移除前缀
  static String removePrefix(String strs, String prefixStr) {
    if (strIsNotEmpty(strs)) {
      if (strs.startsWith(prefixStr)) {
        strs = strs.substring(prefixStr.length);
      }
    }
    return strs;
  }

  ///移除后缀
  static String removePostfix(String strs, String postfix) {
    if (strIsNotEmpty(strs)) {
      if (strs.endsWith(postfix)) {
        strs = strs.substring(0, strs.lastIndexOf(postfix));
      }
    }
    return strs;
  }

  ///show自定义dialog
  static void showCustomDialog(BuildContext context, Widget dialog) {
    showDialog(
      context: context,
      builder: (context) => dialog,
    );
  }

  ///展示自定义BottomSheet
  static void showCustomBottomSheet(BuildContext context, Widget sheet, {bool isDismissible = true}) {
    showModalBottomSheet(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      isDismissible: isDismissible,
      context: context,
      builder: (BuildContext context) {
        return sheet;
      },
    );
  }

  ///补0
  static String packZero(int value) {
    if (value < 10) return '0$value';
    return value.toString();
  }

  ///展示年月日选择器
  static void showYMDPicker(BuildContext context, {String ymdStr, String firstYmdStr, String lastYmdStr, Function callback}) {
    showDatePicker(
      context: context,
      initialDate: strIsEmpty(ymdStr) ? DateTime.now() : DateUtil.getDateTime(ymdStr),
      firstDate: DateUtil.getDateTime(strIsEmpty(firstYmdStr) ? "1990-01-01" : firstYmdStr),
      lastDate: DateUtil.getDateTime(strIsEmpty(lastYmdStr) ? "2100-12-31" : lastYmdStr),
    ).then((DateTime val) {
      if (val != null) {
        callback(DateUtil.formatDate(val, format: DataFormats.y_mo_d));
      }
    }).catchError((err) {
      print(err);
    });
  }

  ///展示时分选择器
  static void showHMPicker(BuildContext context, {String hmStr, Function callback}) {
    TimeOfDay initialTime;
    if (strIsNotEmpty(hmStr) && hmStr.contains(":")) {
      List<String> split = hmStr.split(":");
      int hour = int.parse(split[0]);
      int minute = int.parse(split[1]);
      initialTime = TimeOfDay(hour: hour, minute: minute);
    } else {
      initialTime = TimeOfDay.now();
    }

    showTimePicker(
      context: context,
      initialTime: initialTime,
    ).then((TimeOfDay val) {
      if (val != null) {
        callback("${packZero(val.hour)}:${packZero(val.minute)}");
      }
    }).catchError((err) {
      print(err);
    });
  }

  ///展示年月日时分选择器
  static void showYMDHMPicker(BuildContext context, {String ymdhmStr, String firstYmdStr, String lastYmdStr, Function callback}) {
    if (strIsEmpty(ymdhmStr)) {
      ymdhmStr = DateUtil.getNowDateStr();
    }

    List<String> split = ymdhmStr.split(" ");
    String ymdStr = split[0];
    String hmStr = split[1];

    showYMDPicker(
      context,
      ymdStr: ymdStr,
      firstYmdStr: firstYmdStr,
      lastYmdStr: lastYmdStr,
      callback: (val) {
        String ymdStr = val;
        showHMPicker(context, hmStr: hmStr, callback: (val) {
          callback("$ymdStr $val");
        });
      },
    );
  }

  ///获取颜色的16进制文本值
  static String getColorText(Color color) {
    String str = color.value.toRadixString(16).substring(2);
    return "#$str";
  }

  ///拼接对象集合里的字段
  static String joinFields(List list, {String field}) {
    String str = parseObj2Json(list);
    List<dynamic> dynamicList = parseJson2List(str);

    StringBuffer sb = StringBuffer();
    dynamicList.forEach((item) {
      String str;
      if (strIsNotEmpty(field)) {
        str = item[field];
      } else {
        str = item.toString();
      }
      sb..write(str)..write(",");
    });
    return removePostfix(sb.toString(), ",");
  }
}
